package reflection;

import com.alibaba.fastjson.JSON;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * 动态的创建对象通过反射
 */
public class Test06 {
    public static void main(String[] args) throws ClassNotFoundException, IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException {
        //获得Class对象
        Class c1 = Class.forName("reflection.User");
        //构造一个对象
        User user = (User) c1.newInstance();
        System.out.println(JSON.toJSONString(user));

        //得到包名+类名+地址
        System.out.println(user);

        //通过构造器创建对象
        Constructor<User> constructor = c1.getDeclaredConstructor(String.class, int.class, int.class);
        User user2 = constructor.newInstance("分界线", 1, 21);
        System.out.println(user2);
        //System.out.println(JSON.toJSONString(user2));

        Constructor constructor1 = c1.getDeclaredConstructor(String.class, int.class, int.class);
        User user1 = (User) constructor1.newInstance("张三", 2, 18);
        System.out.println(JSON.toJSONString(user1));
        System.out.println("------------------------------");
        //通过反射调用普通方法
        User user3 = (User) c1.newInstance();
        //通过反射获取一个方法
        Method setName = c1.getDeclaredMethod("setName", String.class);
        //invoke:激活的意思
        //(对象,"方法的值")
        setName.invoke(user3, "分界线");
        System.out.println(user3.getName());
    }
}
